package com.jp.fm.datacollector;

import java.text.NumberFormat;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.jp.fm.HomeFinanceRunner;
import com.jp.fm.dao.AccountDao;
import com.jp.fm.data.Account;
import com.jp.fm.data.UserAccount;

public class SelAmex extends SelParent {

	private WebDriver driver;

	@Before
	public final void setUp() throws Exception {
		this.driver = new FirefoxDriver();
		this.driver.manage().timeouts()
				.implicitlyWait(AllTests.WAIT_TIME_SECONDS, TimeUnit.SECONDS);
	}

	@Test
	public final void testSelAmex() throws Exception {

		// Lookup username, password and url
		UserAccount uAcct = UserAccount.findByRunClass(this.getClass()
				.getName());
		String url = uAcct.getAttribute(UserAccount.URL);
		String username = uAcct.getUsername();
		String password = uAcct.getPassword();
		String name = uAcct.getName();

		this.driver.get(url);

		driver.findElement(By.id("LabelUserID")).click();
		driver.findElement(By.id("UserID")).click();
		driver.findElement(By.id("UserID")).clear();
		driver.findElement(By.id("UserID")).sendKeys(username);
		driver.findElement(By.id("Password")).clear();
		driver.findElement(By.id("Password")).sendKeys(password);
		driver.findElement(By.id("loginImage")).click();

		String balanceStr = driver.findElement(By.id("outstandingAmtHeader"))
				.getText();
		Number number = NumberFormat.getInstance().parse(balanceStr);
		Float balance = number.floatValue();

		driver.findElement(By.id("iNavLnkLog")).click();

		// Update account balance
		Account account = getAccountDao().findByName(name);
		balance *= -1;
		account.setBalance(balance);
		getAccountDao().writeObject(account);
		System.out.println("Account updated");

		// System.out.println(insertCount + " records inserted");

		HomeFinanceRunner.getCache(AccountDao.CACHE_NAME).removeAll();
		System.out.println("Account< " + account.getName() + "> cache cleared");
	}

	@After
	public final void tearDown() throws Exception {
		this.driver.quit();
	}

}
